package com.demo.modules.sys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import com.demo.common.annotation.SysLog;
import com.demo.common.constant.Constant;
import com.demo.common.base.controller.BaseController;
import com.demo.common.utils.PageUtils;
import com.demo.common.utils.PoiUtils;
import com.demo.common.base.R;
import com.demo.common.validator.BaseAssert;
import com.demo.common.validator.ValidatorUtils;
import com.demo.common.validator.group.AddGroup;
import com.demo.common.validator.group.UpdateGroup;
import com.demo.modules.sys.entity.SysUserEntity;
import com.demo.modules.sys.form.PasswordForm;
import com.demo.modules.sys.form.SysUserQueryForm;
import com.demo.modules.sys.form.SysUserUpdateBatchForm;
import com.demo.modules.sys.service.SysUserRoleService;
import com.demo.modules.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 系统用户
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {
    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;


    /**
     * 查询分页数据
     */
    @GetMapping("/page")
    public R<PageUtils<SysUserEntity>> page(SysUserQueryForm params) {

        PageUtils<SysUserEntity> page = sysUserService.queryPage(params);

        return R.ok(page);
    }

    /**
     * 查询列表数据
     */
    @GetMapping("/list")
    public R<List<SysUserEntity>> list(SysUserQueryForm params) {

        List<SysUserEntity> list = sysUserService.queryList(params);

        return R.ok(list);
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    public R<SysUserEntity> info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);
        user.setPassword(null);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok(user);
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        BaseAssert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 保存用户
     */
    @SysLog("新增用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);

        sysUserService.saveUser(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setCreator(getUserId());
        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, Constant.SUPER_ADMIN)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }

    /**
     * 批量更新
     */
    @SysLog("批量更新")
    @PostMapping("/updateBatch")
    @RequiresPermissions("sys:user:update")
    public R updateBatch(@RequestBody SysUserUpdateBatchForm form) {
        sysUserService.updateBatch(form.getUser(), form.getUserIds());

        return R.ok();
    }

    /**
     * 导出用户列表
     */
    @GetMapping("/export")
    @RequiresPermissions("sys:user:export")
    public ResponseEntity export(SysUserQueryForm params) throws IOException {
        String name = "人员列表";

        List<SysUserEntity> users = sysUserService.queryList(params);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(name, "Sheet1"), SysUserEntity.class, users);

        return PoiUtils.export(workbook, name + DateUtil.formatDateTime(new Date()) + ".xls");
    }

    /**
     * 导入用户
     */
    @PostMapping("/import")
    @SysLog("导入用户")
    @RequiresPermissions("sys:user:import")
    public R importUser(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {

        //执行导入
        ExcelImportResult<SysUserEntity> result = PoiUtils.importExcel(file.getInputStream(), SysUserEntity.class);

        // 数据处理
        result.getList().forEach(user -> {
            String salt = RandomStringUtils.randomAlphanumeric(20);
            user.setSalt(salt);
            user.setPassword(new Sha256Hash("123456", salt).toHex());
        });

        // 批量写入数据库
        sysUserService.saveBatch(result.getList());

        return R.ok("成功导入" + result.getList().size() + "条数据");
    }
}
